<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="系统名称" prop="subsystemName">
        <el-input
          v-model="queryParams.subsystemName"
          placeholder="请输入子系统名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:subsystem:add']"
        >新增</el-button>
      </el-col>
<!--      <el-col :span="1.5">
        <el-button
          type="success"
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:subsystem:edit']"
        >修改</el-button>
      </el-col>-->
      <el-col :span="1.5">
        <el-button
          type="danger"
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:subsystem:remove']"
        >删除</el-button>
      </el-col>
<!--      <el-col :span="1.5">
        <el-button
          type="warning"
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:subsystem:export']"
        >导出</el-button>
      </el-col>-->
      <div class="top-right-btn">
        <el-tooltip class="item" effect="dark" content="刷新" placement="top">
          <el-button size="mini" circle icon="el-icon-refresh" @click="handleQuery" />
        </el-tooltip>
        <el-tooltip class="item" effect="dark" :content="showSearch ? '隐藏搜索' : '显示搜索'" placement="top">
          <el-button size="mini" circle icon="el-icon-search" @click="showSearch=!showSearch" />
        </el-tooltip>
      </div>
    </el-row>

    <el-table v-loading="loading" :data="subsystemList" @selection-change="handleSelectionChange" :max-height="height">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" width="70" align="center" fixed="left">
        <template scope="scope"> <span>{{scope.$index + (queryParams.pageNum - 1) * queryParams.pageSize + 1}} </span> </template>
      </el-table-column>
      <el-table-column label="子系统名称" align="center" prop="subsystemName" :show-overflow-tooltip="true" min-width="160"/>
      <!--<el-table-column label="路径" align="center" prop="subsystemUrl" :show-overflow-tooltip="true"/>-->
      <el-table-column label="图片" align="center" prop="subsystemImg">
        <template slot-scope="scope">
          <img :src="scope.row.subsystemImg" style="width: 30px;height: 30px;vertical-align: middle;" v-if="scope.row.subsystemImg!=null">
        </template>
      </el-table-column>
      <el-table-column label="显示顺序" align="center" prop="orderNum" />
      <el-table-column label="二级菜单" align="center" prop="openMenu" :formatter="openMenuFormat" />
      <el-table-column label="状态" align="center" width="100">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.substatus"
            active-value="0"
            inactive-value="1"
            @change="handleStatusChange(scope.row)"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="创建人" align="center" prop="createName" />
      <el-table-column label="创建时间" align="center" prop="createTime" width="140">
        <template slot-scope="scope">
          <span>{{ scope.row.createTime }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="160">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:subsystem:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:subsystem:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改子系统管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="系统名称" prop="subsystemName">
          <el-input v-model="form.subsystemName" placeholder="请输入子系统名称" />
        </el-form-item>
        <el-form-item label="系统路径" prop="subsystemUrl">
          <el-input v-model="form.subsystemUrl" placeholder="请输入子系统路径" />
        </el-form-item>
        <el-form-item label="图片地址" prop="subsystemImg">
          <el-upload
            ref="upload"
            class="avatar-uploader"
            accept=".jpg, .jpeg, .gif, .png"
            :action="upload.url"
            :headers="upload.headers"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload">
            <img v-if="upload.imageUrl" :src="upload.imageUrl" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
          <span style="color: red;font-size: 12px">请上传分辨率宽度和高度相等的图片!</span>
        </el-form-item>
        <el-form-item label="显示顺序" prop="orderNum">
          <el-input-number v-model="form.orderNum" controls-position="right" :min="0" style="width: 100%;" placeholder="请输入显示顺序" />
        </el-form-item>
        <el-form-item label="二级菜单" prop="openMenu">
          <el-select v-model="form.openMenu" placeholder="请选择二级菜单">
            <el-option label="关闭" value="0" />
            <el-option label="打开" value="1" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="form.substatus">
            <el-radio
              v-for="dict in statusOptions"
              :key="dict.dictValue"
              :label="dict.dictValue"
            >{{dict.dictLabel}}</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<style>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>

<script>
import { listSubsystem, getSubsystem, delSubsystem, addSubsystem, updateSubsystem, exportSubsystem, getSubsystemByName, changeSubsystemStatus } from "@/api/system/subsystem";
import { getToken } from "@/utils/auth";

export default {
  name: "Subsystem",
  data() {
    return {
      height: (document.documentElement.clientHeight || document.body.clientHeight)-260,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      names: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 子系统管理表格数据
      subsystemList: [],
      // 状态数据字典
      statusOptions: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        subsystemName: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        subsystemName: [
          { required: true, message: "系统名称不能为空", trigger: "blur" }
        ],
      },
      upload: {
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/common/upload",
        // 上传的文件列表
        imageUrl: ''
      },
    };
  },
  created() {
    this.getList();
    this.getDicts("sys_normal_disable").then(response => {
      this.statusOptions = response.data;
    });
  },
  methods: {
    /** 查询子系统管理列表 */
    getList() {
      this.loading = true;
      listSubsystem(this.queryParams).then(response => {
        this.subsystemList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        subsystemId: null,
        subsystemName: null,
        subsystemUrl: null,
        subsystemImg: null,
        createName: null,
        createTime: null,
        updateTime: null,
        orderNum: undefined,
        openMenu: "0",
        substatus: "0",
        delFlag: 0
      };
      this.upload.imageUrl = '';
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.subsystemId)
      this.names = selection.map(item => item.subsystemName)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加子系统管理";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const subsystemId = row.subsystemId || this.ids
      getSubsystem(subsystemId).then(response => {
        this.form = response.data;
        this.form.openMenu = ""+this.form.openMenu+"";
        this.upload.imageUrl = this.form.subsystemImg;
        this.open = true;
        this.title = "修改子系统管理";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          getSubsystemByName(this.form.subsystemName).then(response => {
            if (response.data!=undefined && response.data.subsystemId!=null && response.data.subsystemId!=this.form.subsystemId){
              this.msgError("系统名称已存在，提交失败，请修改！");
            }else {
              if (this.form.subsystemId != null) {
                updateSubsystem(this.form).then(response => {
                  if (response.code === 200) {
                    this.msgSuccess("修改成功");
                    this.open = false;
                    this.getList();
                  }
                });
              } else {
                addSubsystem(this.form).then(response => {
                  if (response.code === 200) {
                    this.msgSuccess("新增成功");
                    this.open = false;
                    this.getList();
                  }
                });
              }
            }
          });
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const subsystemIds = row.subsystemId || this.ids;
      const subsystemNames = row.subsystemName || this.names;
      this.$confirm('是否确认删除子系统名称为"' + subsystemNames + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delSubsystem(subsystemIds);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(function() {});
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有子系统管理数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return exportSubsystem(queryParams);
        }).then(response => {
          this.download(response.msg);
        }).catch(function() {});
    },
    handleAvatarSuccess(res, file) {
      this.asyncImgChecked(file).then(data => {
        if (!data) {
          this.upload.imageUrl = '';
          this.form.subsystemImg = null;
        }else {
          this.upload.imageUrl = URL.createObjectURL(file.raw);
          this.form.subsystemImg = res.url;
        }
      });
    },
    //附件上传前检测
    beforeAvatarUpload(file) {
      const isfileSize = file.size / 1024 / 1024 < 500;
      if (!isfileSize) {
        this.msgError('上传文件大小不能超过500MB!');
        return isfileSize;
      }
    },
    asyncImgChecked(file) {
      return new Promise((resolve, reject) => {
        let reader = new FileReader();
        reader.readAsDataURL(file.raw); // 必须用file.raw
        reader.onload = () => { // 让页面中的img标签的src指向读取的路径
          let img = new Image();
          img.src = reader.result;
          if (img.complete) { // 如果存在浏览器缓存中
            if (img.width != img.height ) {
              this.msgError(`请上传分辨率宽度和高度相等的图片`);
              resolve(false)
            }else {
              resolve(true)
            }
          } else {
            img.onload = () => {
              if (img.width != img.height ) {
                this.msgError(`请上传分辨率宽度和高度相等的图片`);
                resolve(false)
              }else {
                resolve(true)
              }
            }
          }
        };
      })
    },
    // 状态修改
    handleStatusChange(row) {
      let text = row.substatus === "0" ? "启用" : "停用";
      this.$confirm('确认要"' + text + '""' + row.subsystemName + '"子系统吗?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function() {
        return changeSubsystemStatus(row.subsystemId, row.substatus);
      }).then(() => {
        this.msgSuccess(text + "成功");
      }).catch(function() {
        row.status = row.status === "0" ? "1" : "0";
      });
    },
    openMenuFormat(row, column){
      if (row.openMenu==0){
        return "关闭";
      } else {
        return "打开";
      }
    }
  }
};
</script>
